#include "EditorCallStackAbilityViewModel.h"

#include "Asset/EditorDefaultPackage.h"

#include "Framework/Editor.h"
#include "Language/EditorScriptDebugSubsystem.h"

#include "Window/EditorWindowGroupModel.h"

void REditorCallStackAbilityViewModel::BindModel(TSharedObjectPtr<REditorAbilityModel> InModel)
{
    Super::BindModel(InModel);
    CallStackModel = InModel;

    Icon = REditorDefaultPackage::Get()->GetIcon(U"CodiconDebugAlt");
    HighlightIcon = REditorDefaultPackage::Get()->GetIcon(U"CodiconDebugAlt_Highlight");


    REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>()
        ->OnCallStackChanged.BindLambda([this]()
    {
        OnCallStackChanged.ExecuteIfBound();
    });
}

TSharedObjectPtr<RTexture2D> REditorCallStackAbilityViewModel::GetIcon() const
{
    return Icon;
}

TSharedObjectPtr<RTexture2D> REditorCallStackAbilityViewModel::GetHighlightIcon() const
{
    return HighlightIcon;
}

int64_t REditorCallStackAbilityViewModel::GetCallStackFrameNum() const
{
    return REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>()->GetCallStackFrameNum();
}

CString REditorCallStackAbilityViewModel::GetCallStackFrameFunctionName(int64_t InIndex) const
{
    return REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>()->GetCallStackFrameFunctionName(InIndex);
}

CString REditorCallStackAbilityViewModel::GetCallStackFrameFileName(int64_t InIndex) const
{
    return REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>()->GetCallStackFrameFileName(InIndex);
}

int64_t REditorCallStackAbilityViewModel::GetCallStackFrameLineNumber(int64_t InIndex) const
{
    return REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>()->GetCallStackFrameLineNumber(InIndex);
}

void REditorCallStackAbilityViewModel::OnFrameClicked(int64_t InIndex)
{
    REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>()
        ->SelectFrame(InIndex);

    //open the file
    auto FileName=GetCallStackFrameFileName(
        REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>()
        ->GetSelectedFrame());
    REditorWindowGroupModel::Get()->OpenFile(FileName);
}

bool REditorCallStackAbilityViewModel::IsFrameSelected(int64_t InIndex) const
{
    return REditor::Get()->GetSubsystem<REditorScriptDebugSubsystem>()
        ->GetSelectedFrame()
     == InIndex;
}


bool REditorCallStackAbilityViewModel::IsFrameHovered(int64_t InIndex) const
{
    return HoveredFrameIndex == InIndex;
}

void REditorCallStackAbilityViewModel::HoverFrame(int64_t InIndex)
{
    HoveredFrameIndex = InIndex;
}

void REditorCallStackAbilityViewModel::UnhoverFrame(int64_t InIndex)
{
    if (HoveredFrameIndex == InIndex)
    {
        HoveredFrameIndex = -1;
    }
}


